package com.yxuan.springboot.controller;


import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.yxuan.springboot.CustomizedException.DefaultException;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.service.*;
import com.yxuan.springboot.util.Code;
import com.yxuan.springboot.util.ResolveTokenUtil;
import com.yxuan.springboot.util.Result;
import com.yxuan.springboot.constant.config.WxPayConfig;
import com.yxuan.springboot.douyinPayUtil.DouYinUtil;

import com.yxuan.springboot.util.WxPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.yxuan.springboot.douyinPayUtil.DyPayCommon.*;

@Slf4j
@RestController
@RequestMapping("/dypay")
@Api(tags = "抖音支付")
public class DouyinPayController {


    @Autowired
    private UserLoginService userLoginService;

/*    @Autowired
    private WxPayConfig wxPayConfig;

    @Autowired
    private Verifier verifier;

    @Autowired
    private CloseableHttpClient wxPayClient;*/

    @Autowired
    private OrdersService ordersService;

//    @Autowired
//    private UserVipService userVipService;

//    @Autowired
//    private WxPayUtil wxPayUtil;

    @Value("${douyin.appid}")
    private String DY_APP_ID;

//    @Autowired
//    private GoodsService goodsService;
//
//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private ThirdTokenService thirdTokenService;

    @Autowired
    private DyPayService dyPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource(name = "wxPayClient")
    private CloseableHttpClient dyPayClient;
    @Value("${douyin.token}")
    private String TOKEN;
    @Value("${douyin.notify_url}")
    private String DY_NOTIFY_URL;

    public String imgUrl="https://volunteer-1318337852.cos.ap-nanjing.myqcloud.com/1/865071687779536275.jpg";
    /**
     * 获取支付的请求参数
     */
    @ApiOperation(value = "获取支付的请求参数")
    @RequestMapping("/dyprepay")
    public Result payPrepay(HttpServletRequest request, String orderId) throws Exception {
        log.info("---------orderId：{}", orderId);
        //根据订单号查询订单信息，给基础数据设置基础值
        UserLogin userLogin = ResolveTokenUtil.targetLogin(request.getHeader("token"));
        UserLogin targetUserLogin = userLoginService.findObjectByPramas(userLogin);
        String dyOpenId = targetUserLogin.getOpenId().substring(2);
        log.info("抖音openid:"+dyOpenId);

        Orders orders = new Orders();
        orders.setUserLoginId(targetUserLogin.getId().toString());
        orders.setOrderId(orderId);
        Orders targetOrder = ordersService.findObjectByPramas(orders);

        //之前同步地方



        log.info("给必要参数赋值");
        Map<String, Object> parame = new LinkedHashMap<>();
        //抖音小程序app
        parame.put("app_id", DY_APP_ID);
        // 商户订单编号
        parame.put("out_order_no", orderId);
        //支付金额
        parame.put("total_amount", targetOrder.getTotal().multiply(new BigDecimal(100)).intValue());
        log.info("金额：" + parame.get("total_amount"));
        // 商品标题
        parame.put("subject", targetOrder.getName());
        // 商品描述（不能为空）
        parame.put("body", targetOrder.getName());
        // 回调地址（与支付设置中一致）
        parame.put("notify_url", DY_NOTIFY_URL);
        // 时间(900秒)
        parame.put("valid_time", 900);
        // 支付密钥
        String sign = DouYinUtil.getSign(parame);
        log.info("支付下单密钥签名：{}", sign);
        // 数字签证
        parame.put("sign", sign);

        Map getpost = getpost(parame, dyPayClient);

        log.info("getpost:" + getpost);

//        JSONObject sessionData1 = JSON.parseObject(res);
//        if ("0".equalsIgnoreCase(sessionData1.getString("err_no"))) {
//            log.info("支付请求成功");
//            JSONObject sessionData = sessionData1.getJSONObject("data");
//            Map<String, Object> resultObj = new HashMap();
//            String prepayId = sessionData.getString("order_id");
//            resultObj.put("err_no",sessionData1.getString("err_no"));
//            resultObj.put("order_id",prepayId);
//            resultObj.put("order_token",sessionData.getString("order_token"));
//            return new Result(resultObj,SUCCESSCODE,"支付请求成功");
//        }else{
//            log.info("支付失败");
//            Map<String, Object> resultObj = new HashMap<>();
//            resultObj.put("err_no",sessionData1.getString("err_no"));
//            return new Result(FAILCODE,"支付请求失败");
//        }

        log.info("订单同步");
        //获取抖音access_token
        ThirdToken thirdToken = new ThirdToken();
        thirdToken.setTokenType("抖音小程序token");
        ThirdToken dyAccessTokenObject = thirdTokenService.findObjectByPramas(thirdToken);
        long createTime = targetOrder.getCreateTime().getTime();
        String status="待支付";
        BigDecimal multiply = targetOrder.getTotal().multiply(new BigDecimal("100"));
        Long multiplyLong = multiply.longValue();
        log.info(multiplyLong.toString() +"================");
        List<Map<String,Object>> item = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        //抖音小程序app
        map.put("item_code", orderId); //开发者侧商品 ID，长度 <= 64 byte
        // 商户订单编号
        map.put("img", imgUrl);
        //支付金额
        map.put("title", targetOrder.getName()); //子订单商品介绍标题，长度 <= 256 byte
        map.put("price", multiplyLong); //单类商品的总价，单位为分
        item.add(map);
        String order_detail = dyPayService.order_detail(orderId, createTime, status, multiply.longValue(), item);

        dyPayService.orderSynchronization(dyAccessTokenObject.getAccessToken(),dyOpenId,order_detail,0);

        log.info("订单同步请求完成");



        return new Result(getpost.get("data"), Code.SUCCESSCODE, "抖音支付请求成功");
    }

    public static Map getpost(Map<String, Object> parame, CloseableHttpClient dyPayClient) throws DefaultException {

        // 2.获取请求对象
        log.info("获取请求对象");

        HttpPost httpPost = getDYHttpPost(parame);


        // 3.完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = dyPayClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();

        }

        // 4.解析response对象
        HashMap<String, String> resultMap = resolverResponse(response);
        if (resultMap != null) {

            return resultMap;
        }
        return null;


    }


    public static Map getDDpost(Map<String, Object> parame, CloseableHttpClient dyPayClient) throws DefaultException {

        // 2.获取请求对象
        log.info("获取请求对象");

        HttpPost httpPost = getDDHttpPost(parame);

        // 3.完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = dyPayClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();

        }

        // 4.解析response对象
        HashMap<String, String> resultMap = resolverResponse(response);
        if (resultMap != null) {

            return resultMap;
        }
        return null;


    }


    public static Map getDSpost(Map<String, Object> parame, CloseableHttpClient dyPayClient) throws DefaultException {

        // 2.获取请求对象
        log.info("获取请求对象");

        HttpPost httpPost = getDSHttpPost(parame);


        // 3.完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = dyPayClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();

        }

        // 4.解析response对象
        HashMap<String, String> resultMap = resolverResponse(response);
        if (resultMap != null) {

            return resultMap;
        }
        return null;


    }
    @ApiOperation(value = "抖音订单回调接口")
    @RequestMapping(value = "/dycallback", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object dynotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            InputStream in = request.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
            String responseJson = new String(out.toByteArray(), "utf-8");
            log.info("responseJson：{}", responseJson);
            JSONObject jsonObject = JSONObject.parseObject(responseJson);
            JSONObject msgJson = jsonObject.getJSONObject("msg");
            String resultCode = jsonObject.getString("type");
            if ("payment".equalsIgnoreCase(resultCode)) {
                List<String> sortedString = new ArrayList<>();
                //token
                sortedString.add(this.TOKEN);
                //时间戳
                sortedString.add(jsonObject.getString("timestamp"));
                //随机数
                sortedString.add(jsonObject.getString("nonce"));
                //msg
                sortedString.add(jsonObject.getString("msg"));
//                Collections.sort(sortedString);
//                StringBuilder sb = new StringBuilder();
//                sortedString.forEach(sb::append);
                String msg_signature = jsonObject.getString("msg_signature");
                String sign = DouYinUtil.callbackSign(sortedString);
                log.info("支付回调接口密钥签名：{}", sign);
                if (!sign.equals(msg_signature)) {//判断签名
                    log.info("验签失败");
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("err_no", 8);
                    resultJson.put("err_tips", "error");
                    return resultJson.toString();
                }
                JSONObject resultJson = new JSONObject();
                resultJson.put("err_no", 0);
                resultJson.put("err_tips", "success");
                //支付成功后的业务逻辑
                String orderId = msgJson.getString("cp_orderno");

                log.info("支付成功");

                //查询订单状态是否已支付，若已支付则跳过
                Orders orders = new Orders();
                orders.setOrderId(orderId);
                orders.setOrdersState("1");
                Orders objectByPramas = null;
                try {
                    objectByPramas = ordersService.findObjectByPramas(orders);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (objectByPramas == null) {

                    try {

                        //        修改订单状态
                        // 交换机名称
                        String exchange = "wxzhifu.exchange";
                        // 发送消息
                        rabbitTemplate.convertAndSend(exchange,"wx", orderId);
//                        ordersService.upd(orders);
//
//                        Orders targetOrder = ordersService.findObjectByPramas(orders);
//
//
//
//                        log.info("订单同步");
//                        //找userlogin
//                        UserLogin userLogin = new UserLogin();
//                        userLogin.setId(Integer.valueOf(targetOrder.getUserLoginId()));
//                        UserLogin tagetUser = userLoginService.findObjectByPramas(userLogin);
//                        String dyOpenId = tagetUser.getOpenId().substring(2);
//                        //获取抖音access_token
//                        ThirdToken thirdToken = new ThirdToken();
//                        thirdToken.setTokenType("抖音小程序token");
//                        ThirdToken dyAccessTokenObject = thirdTokenService.findObjectByPramas(thirdToken);
//                        long createTime = targetOrder.getCreateTime().getTime();
//                        String status="已支付";
//                        BigDecimal multiply = targetOrder.getTotal().multiply(new BigDecimal("100"));
//
//                        List<Map<String,Object>> item = new ArrayList<>();
//                        Map<String, Object> map = new HashMap<>();
//                        //抖音小程序app
//                        map.put("item_code", orderId); //开发者侧商品 ID，长度 <= 64 byte
//                        // 商户订单编号
//                        map.put("img", imgUrl);
//                        //支付金额
//                        map.put("title", targetOrder.getName()); //子订单商品介绍标题，长度 <= 256 byte
//
//                        map.put("price", multiply.longValue()); //单类商品的总价，单位为分
//                        item.add(map);
//                        String order_detail = dyPayService.order_detail(orderId, createTime, status, multiply.longValue(), item);
//
//                        dyPayService.orderSynchronization(dyAccessTokenObject.getAccessToken(),dyOpenId,order_detail,1);
//                        log.info("订单同步请求完成");
//
//
//
//                        Orders orders1 = ordersService.findObjectByPramas(orders);
////      搜索该商品的名称
//                        Goods goods = new Goods();
//                        goods.setId(Integer.valueOf(orders1.getGoodsId()));
//                        Goods goods1 = goodsService.findObjectByPramas(goods);
//
//                        UserVip userVip = new UserVip();
//                        userVip.setUserId(Integer.valueOf(targetOrder.getUserLoginId()));
//                        UserVip userVip1 = userVipService.findObjectByPramas(userVip);
//                        String vipRankMyself = userVip1.getVipRank();
//
//                        Integer getGptTimes = 0;
//                        if (userVip1.getGptTimes() == null || userVip1.getGptTimes().equals("")) {
//                            getGptTimes = 0;
//                        } else {
//                            getGptTimes = Integer.valueOf(userVip1.getGptTimes());
//                        }
//
//                        Integer getInfoUpdTimes = 0;
//                        if (userVip1.getInfoUpdTimes() == null || userVip1.getInfoUpdTimes().equals("")) {
//                            getInfoUpdTimes = 0;
//                        } else {
//                            getInfoUpdTimes = Integer.valueOf(userVip1.getInfoUpdTimes());
//                        }
//
//                        Integer getProbabilityTimes = 0;
//                        if (userVip1.getProbabilityTimes() == null || userVip1.getProbabilityTimes().equals("")) {
//                            getProbabilityTimes = 0;
//                        } else {
//                            getProbabilityTimes = Integer.valueOf(userVip1.getProbabilityTimes());
//                        }
//                        switch (goods1.getName()) {
//                            case "日会员":
//                                userVip.setVipRank("1");
//                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
//                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
//                                userVip.setGptTimes(String.valueOf(getGptTimes + 5));
//                                break;
//                            case "周会员":
//                                userVip.setVipRank("2");
//                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
//                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 3));
//                                userVip.setGptTimes(String.valueOf(getGptTimes + 50));
//                                break;
//                            case "月会员":
//                                userVip.setVipRank("3");
//                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
//                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 5));
//                                userVip.setGptTimes(String.valueOf(getGptTimes + 120));
//                                break;
//                            default:
//                                userVip.setVipRank("1");
//                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
//                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
//                                userVip.setGptTimes(String.valueOf(getGptTimes + 5));
//                                break;
//                        }
//
//                        if (Integer.parseInt(userVip.getVipRank()) < Integer.parseInt(vipRankMyself)) {
//                            userVip.setVipRank(vipRankMyself);
//                        }
//
//                        Date nows = new Date(System.currentTimeMillis());
//
//                        if (userVip1.getExpirationTime() == null || userVip1.getExpirationTime().compareTo(nows) < 0) {
//                            LocalDateTime now = LocalDateTime.now();
//                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                            String formattedNow = now.format(formatter);
//                            System.out.println("当前时间：" + formattedNow);
//                            LocalDateTime after10Minutes = null;
//                            if (goods1.getName().equals("日会员")) {
//                                after10Minutes = now.plusMinutes(60 * 24);
//
//                            } else if (goods1.getName().equals("周会员")) {
//                                after10Minutes = now.plusMinutes(60 * 24 * 7);
//
//                            } else if (goods1.getName().equals("月会员")) {
//                                after10Minutes = now.plusMinutes(60 * 24 * 30);
//
//                            } else {
//                                after10Minutes = now.plusMinutes(60 * 24);
//
//                            }
//                            String formattedAfter10Minutes = after10Minutes.format(formatter);
//                            Date expirationTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formattedAfter10Minutes);
//                            userVip.setExpirationTime(expirationTime);
//                        } else {
//                            Date date = userVip1.getExpirationTime();
//
//                            // 使用Calendar类将date转换为Calendar对象
//                            Calendar calendar = Calendar.getInstance();
//                            calendar.setTime(date);
//
//                            // 在Calendar对象上增加24小时
//
//
//                            if (goods1.getName().equals("日会员")) {
//                                calendar.add(Calendar.HOUR_OF_DAY, 24);
//                            } else if (goods1.getName().equals("周会员")) {
//                                calendar.add(Calendar.HOUR_OF_DAY, 24 * 7);
//                            } else if (goods1.getName().equals("月会员")) {
//                                calendar.add(Calendar.HOUR_OF_DAY, 24 * 31);
//                            } else {
//                                calendar.add(Calendar.HOUR_OF_DAY, 24);
//                            }
//                            // 将Calendar对象转换为Date对象
//                            Date newDate = calendar.getTime();
//
//                            // 使用DateTimeFormatter类将Date对象格式化为指定格式的字符串
//                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                            String formattedNewDate = LocalDateTime.ofInstant(newDate.toInstant(), ZoneId.systemDefault()).format(formatter);
//                            // 使用SimpleDateFormat类将字符串转换为Date对象
//                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                            Date expirationTime = null;
//                            try {
//                                expirationTime = sdf.parse(formattedNewDate);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                            System.out.println(expirationTime + "===================");
//
//                            // 调用setExpirationTime方法
//                            userVip.setExpirationTime(expirationTime);
//                            System.out.println(formattedNewDate);
//
//                        }
//                        userVipService.upd(userVip);
//                        UserVip userVip2 = new UserVip();
//                        userVip2.setUserId(Integer.valueOf(targetOrder.getUserLoginId()));
//                        userVipService.findObjectByPramas(userVip2);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


                return resultJson.toString();
            } else {
                //订单编号
                String outTradeNo = msgJson.getString("cp_orderno");
                log.error("订单" + outTradeNo + "支付失败");
                JSONObject resultJson = new JSONObject();
                resultJson.put("err_no", 0);
                resultJson.put("err_tips", "error");
                return resultJson.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resultJson = new JSONObject();
            resultJson.put("err_no", 8);
            resultJson.put("err_tips", "error");
            return resultJson.toString();
        }
    }




}
